package com.dynamicthreadpool.spi.support;

import com.dynamicthreadpool.spi.ThreadPool;
import com.dynamicthreadpool.spi.URL;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 固定大小线程池实现
 * 从Dubbo 2.7版本提取的完整实现
 */
public class FixedThreadPool implements ThreadPool {

    @Override
    public ThreadPoolExecutor getExecutor(URL url) {
        String name = url.getParameter("threadname", "DubboThreadPool");
        int cores = url.getParameter("corethreads", url.getParameter("threads", 200));
        int threads = url.getParameter("threads", 200);
        int queues = url.getParameter("queues", 0);
        return new ThreadPoolExecutor(cores, threads, 0, TimeUnit.MILLISECONDS,
                queues == 0 ? new SynchronousQueue<Runnable>() :
                        (queues < 0 ? new LinkedBlockingQueue<Runnable>()
                                : new LinkedBlockingQueue<Runnable>(queues)),
                new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url));
    }

    /**
     * 同步队列
     */
    static class SynchronousQueue<E> extends java.util.concurrent.SynchronousQueue<E> {
        private static final long serialVersionUID = -3223015665454128626L;

        @Override
        public String toString() {
            return "SynchronousQueue(0)";
        }
    }

    /**
     * 命名内部线程工厂
     */
    static class NamedInternalThreadFactory extends NamedThreadFactory {
        public NamedInternalThreadFactory(String prefix, boolean daemon) {
            super(prefix, daemon);
        }
    }
}